/*
 * @Author: zi.yang
 * @Date: 2021-05-23 22:49:50
 * @LastEditors: zi.yang
 * @LastEditTime: 2021-10-04 23:58:22
 * @Description: token
 * @FilePath: \project-management\utils\jwt.js
 */
// 引入模块依赖
const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');

// 创建 token 类
class Jwt {
  constructor(data, exp = false) {
    this.exp = exp;
    this.data = data;
  }
  // 重新生成 token
  refreshToken() {
    let data = this.data;
    let created = Math.floor(Date.now() / 1000);
    let cert = fs.readFileSync(path.join(__dirname, '../pem/private_key.pem'));
    let token = jwt.sign(
      {
        data,
        exp: this.exp || created + 60 * 30, // 过期时间
        iat: created, // 创建时间
      },
      cert,
      { algorithm: 'RS256' }
    );
    return token;
  }
  //生成token
  generateToken() {
    let data = this.data;
    let created = Math.floor(Date.now() / 1000);
    let cert = fs.readFileSync(path.join(__dirname, '../pem/private_key.pem'));
    let token = jwt.sign(
      {
        data,
        exp: this.exp || created + 60 * 30, // 过期时间默认 30 分钟
        iat: created, // 创建时间
      },
      cert,
      { algorithm: 'RS256' }
    );
    return token;
  }

  // 校验token
  verifyToken(data) {
    if (data) {
      this.data = data;
    }
    let token = this.data;
    if (token.startsWith('Bearer ')) {
      // Remove Bearer from string
      token = token.slice(7, token.length).trimLeft();
    }
    let cert = fs.readFileSync(path.join(__dirname, '../pem/public_key.pem'));
    let res;
    try {
      let result = jwt.verify(token, cert, { algorithms: ['RS256'] }) || {};
      let { exp = 0 } = result,
        current = Math.floor(Date.now() / 1000);
      if (current <= exp) {
        res = result.data || {};
      }
    } catch (e) {
      res = 'err';
    }
    return res;
  }
}

module.exports = Jwt;
